﻿DECLARE @StatDate datetime
DECLARE @ApCode integer
DECLARE @ApName varchar
SET @StatDate = DATEADD(D, 0, DATEDIFF(D, 0, GETDATE()))
SET @ApCode = 365
SET @ApName = 'lanka'

SELECT 
  md.datetime_in as SendTime, 
  ab.surname as ToName,
  md.msg_size,
  mk.comments,
  md.msg_cirkul,
  md.msg_id,
  md.msg_kind,
  e.item as InfoCode,
  al.item as AliasName,
  h.item as HostName,
  md.from_abonent_id,
  md.to_abonent_id
FROM mon400_data md
INNER JOIN mon400_hostnames h ON md.hostname_id = h.id
INNER JOIN mon400_abonents ab ON md.to_abonent_id = ab.id
INNER JOIN mon400_aliases al ON md.alias_sender_id = al.id
INNER JOIN mon400_errorcodes e ON md.msg_errorcode_id = e.id
INNER JOIN mon400_msg_categories mk ON md.msg_category = mk.item
WHERE
  (md.msurname = @ApName) 
  AND (md.from_abonent_id = ab.id)
  AND (md.datetime_in BETWEEN @StatDate AND (@StatDate + 1))
)
ORDER BY
  md.datetime_in, md.msg_cirkul